package com.usian.article.filter;

import com.usian.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Order(1)
@WebFilter(filterName = "userFilter",urlPatterns = "/api/*")
public class UserFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.从请求头中获取用户id
        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        String userId = httpServletRequest.getHeader("userId");
        log.info("#######获取到用户id，{}",userId);
        //2.将用户id绑定到当前线程
        if(StringUtils.isNotBlank(userId)){
            UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        }
        //3.放行过滤器
        chain.doFilter(request,response);


    }
}
